import time
from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'

port = 1883
topic = "/public/01Studio/1"
# Generate a Client ID with the subscribe prefix.
client_id = 'python'
# 初始化全局变量保存最新的图像数据和是否传输完成
latest_surface = b""
sending_over = False


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n" % rc)

    # client = mqtt_client.Client(client_id)
    client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)
    client.username_pw_set(username="K210_CAMERA", password="mynameisvan0")  # 设置用户名和密码
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        # print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        with open("image.png", 'wb') as f:
            f.write(msg.payload)

        global latest_surface
        global sending_over
        if msg.payload.startswith(b'\xFF\xD8'):
            sending_over = False  # 图像文件开头
        elif msg.payload.endswith(b'\xFF\xD9'):
            sending_over = True  # 图像文件结尾
        latest_surface += msg.payload
    client.subscribe(topic)
    client.on_message = on_message


def publish(client):
    msg_count = 1
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1
        if msg_count > 5:
            break


client = connect_mqtt()
subscribe(client)
client.loop_start()  # 非阻塞模式启动
while True:
    pass
